package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.itheima.health.common.ValidateCodeType;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.security.SecureRandom;

@Service(interfaceClass = SmsService.class)
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private IAcsClient acsClient;
    @Override
    public void sendVlaidateCode(ValidateCodeType type,String mobile) {
        //生成验证码
        SecureRandom secureRandom = new SecureRandom();
        int code= 1000+(int)(secureRandom.nextDouble()*8999.0);
        log.debug("[短信-发送验证码]code:{}",code);
        //储存验证码
        String redisKey = type.redisKey(mobile);
        try (Jedis jedis=jedisPool.getResource()){
            jedis.setex(redisKey,type.getExpireSeconds(),String.valueOf(code));
        }
//        //构造请求参数
//        CommonRequest request = new CommonRequest();
//        request.setMethod(MethodType.POST);
//        request.setDomain("dysmsapi.aliyuncs.com");
//        request.setVersion("2017-05-25");
//        request.setAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-hangzhou");
//        request.putQueryParameter("PhoneNumbers", mobile);
//        //替换成真实的签名
//        request.putQueryParameter("SignName", "传智健康项目");
//        request.putQueryParameter("TemplateCode", type.getTemplateCode());
//        request.putQueryParameter("TemplateParam", "	{\"assertCode\":\"" + code + "\"}");
//        //发给指定手机
//        try {
//            //发起请求
//            CommonResponse response = acsClient.getCommonResponse(request);
//            log.info("[短信-发送验证码]response:{}", response.getData());
//        } catch (ClientException e) {
//            log.error("[短信-发送验证码]", e);
//        }
    }

    @Override
    public boolean checkValidateCode(ValidateCodeType type,String mobile,  String code) {
        //取出正确的验证码
        //比较用户的输入是否正确
        log.info("[短信-校验验证码]type:{},phone:{},code:{}", type, mobile,code);
        try (Jedis jedis = jedisPool.getResource()) {
            //查询redis里的值
            String expectVal = jedis.get(type.redisKey(mobile));
            //对比是否匹配
            if (!StringUtils.isEmpty(expectVal) && expectVal.equals(code)) {
                //如果匹配则删除redis并返回true
                jedis.del(type.redisKey(mobile));
                return true;
            } else {
                //如果不匹配则返回false
                return false;
            }
        }
    }

//    @PostConstruct
//    public void init(){
//        this.sendVlaidateCode("18833054525");
//    }
}
